import { createRouter, createWebHashHistory, createWebHistory, isNavigationFailure } from "vue-router";
import BasicRoutes from './basic'
import { useUserStore, useRouterStore } from '@/store'
import { FormatTreeList } from "@/utils/format";
import LocalStorage from "@/utils/localStorage";
import SessionStorage from "@/utils/sessionStorage";
// 引入env
const ENV = import.meta.env;
// 页面加载进度模块
import Trickling from "@/utils/trickling";
const baseTitle = import.meta.env.VITE_TITLE
let {
    VITE_USE_HASH,
    VITE_ROUTE_HOME_PATH,
    VITE_ROUTE_LOGIN_PATH,
    VITE_ROUTER_STORAGE,
    VITE_ROUTER_STORAGE_TYPE,
    VITE_ROUTER_STORAGE_KEY
} = ENV
export const router = createRouter({
    history:
        VITE_USE_HASH === 'true'
            ? createWebHashHistory()
            : createWebHistory(),
    routes: BasicRoutes,
    scrollBehavior: () => ({ left: 0, top: 0 }),
})
const originalPush = router.push
const originalReplace = router.replace
router.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}
router.replace = function replace(location) {
    return originalReplace.call(this, location).catch(err => err)
}
router.beforeEach((to, from) => {
    Trickling.start()
    const userStore = useUserStore()
    const { token, userInfo } = userStore
    // 当前访问页面
    const { path } = to
    let From_Path = from.fullPath;
    // 要前往的页面
    let To_Path = to.fullPath;
    // 登录页面
    const loginPath = VITE_ROUTE_LOGIN_PATH
    // 是否是登录页面
    const isLoginPage = path === loginPath
    if (isLoginPage) {
        return true
    }
    //  是否有 Token 用户信息
    if (!token || userInfo === null || Object.keys(userInfo).length === 0) {
        if (To_Path != loginPath) {
            return { path: loginPath, replace: true };
        } else {
            return true
        }
    }
    const routerStore = useRouterStore()
    const { RoutesList } = routerStore
    // 判断菜单
    if (RoutesList.length) {
        const list = router.getRoutes()
        if (list.find(route => route.path === to.path)) {
            return true
        } else {
            return { path: loginPath }
        }
    } else {
        if (VITE_ROUTER_STORAGE == 'true') {
            let initRouter = null
            if (VITE_ROUTER_STORAGE_TYPE == 'localStorage') {
                initRouter = LocalStorage.Get(VITE_ROUTER_STORAGE_KEY)
            } else if (VITE_ROUTER_STORAGE_TYPE == "sessionStorage") {
                initRouter = SessionStorage.Get(VITE_ROUTER_STORAGE_KEY)
            }
            if (!initRouter) {
                if (isLoginPage) {
                    return true
                } else {
                    return { path: loginPath, replace: true }
                }
            }
            let LayoutName = "layout"
            let HasLayout = router.hasRoute(LayoutName)
            if (!HasLayout) {
                return { path: loginPath, replace: true }
            }
            routerStore.SetRoutes(initRouter)
            // 将菜单数据全部进行VueRouter格式化
            let handleList = FormatTreeList(initRouter)
            handleList.forEach(route => router.addRoute(LayoutName, route))
            // 动态添加路由后，此处应当重定向到fullPath，否则会加载404页面内容
            // 当前页和要前往的页面是否相同
            return { ...to, replace: true }
        }
    }
})
router.afterEach((to, from, failure) => {
    if (isNavigationFailure(failure)) {
        console.log('路由跳转失败:', failure);
        return
    }
    let { meta } = to
    let { id, pid } = meta
    const routerStore = useRouterStore()
    // const { RoutesList } = routerStore
    // function findRelatedRoutes(routes, id) {
    //     let result = [];
    //     function traverse(routes, parent) {
    //         routes.forEach(route => {
    //             let meta = route.meta || {};
    //             if (meta.id === id) {
    //                 if (parent) {
    //                     result.push(parent);
    //                 }
    //                 result.push(route);
    //             }
    //             if (route.children && route.children.length > 0) {
    //                 traverse(route.children, route);
    //             }
    //         });
    //     }
    //     traverse(routes);
    //     return result;
    // }
    // const breadcrumbList = findRelatedRoutes(RoutesList, id)
    // 设置面包屑
    // routerStore.SetBreadcrumbList(breadcrumbList)
    const pageTitle = to.meta?.title
    if (pageTitle) {
        document.title = `${pageTitle} | ${baseTitle}`
    }
    else {
        document.title = baseTitle
    }
    setTimeout(() => {
        Trickling.done()
    }, 2000)
})
router.onError((e) => {
    console.log("页面加载错误", e)
    Trickling.done()
})
router.ToLogin = (replace = false) => {
    if (replace) {
        return router.replace({ path: VITE_ROUTE_LOGIN_PATH })
    } else {
        return router.push({ path: VITE_ROUTE_LOGIN_PATH })
    }
}
router.ToHome = (replace = false) => {
    if (replace) {
        return router.replace({ path: VITE_ROUTE_HOME_PATH })
    } else {
        return router.push({ path: VITE_ROUTE_HOME_PATH })
    }
}
export default router